const WebSocket = require('ws');
const { add, find, update, del } = require("../server");
const chat = require('../model/chat')


// 创建一个WebSocketServer的实例，监听端口8080
const wss = new WebSocket.Server({ port: 3005 });


// 封装listen暴露出去
const listen = () => {
    // 监听连接
    wss.on('connection', (ws) => {
        console.log('chat连接进来啦...');
        ws.on('message', async (mes) => {
            let result = JSON.parse(mes);
            try {
                let data = await find(chat)
                ws.send(JSON.stringify(data))
                setInterval(async () => {
                    let data = await find(chat)
                    ws.send(JSON.stringify(data))
                }, 2000)
            } catch (err) {
                console.log(err); 
                let obj = {
                    code: 400,
                    message: "数据查询失败",
                }
                ws.send(JSON.stringify(obj));
            }
        })
    });
}

module.exports = listen;